package com.jty.module_main.ui.fragment

import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ScreenUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.czl.lib_base.config.AppConstants
import com.google.gson.reflect.TypeToken
import com.jty.lib_base.base.BaseBean
import com.jty.lib_base.base.BaseFragment
import com.jty.lib_base.data.bean.GridPictureBean
import com.jty.lib_base.data.bean.OssParams
import com.jty.lib_base.extension.ApiSubscriptHelper
import com.jty.lib_base.oss.UploadOss
import com.jty.lib_base.room.AppDatabase
import com.jty.lib_base.room.bean.CoordinateKill
import com.jty.lib_base.room.bean.GridNoSubmit
import com.jty.lib_base.tsdBlePen.CommitOfflineReq
import com.jty.lib_base.tsdBlePen.TsdPenUtil
import com.jty.lib_base.tsdBlePen.TsdService
import com.jty.lib_base.utils.*
import com.jty.lib_base.widget.graffiti.GraffitiOnTouchGestureListener
import com.jty.lib_base.widget.graffiti.GraffitiTouchDetector
import com.jty.lib_base.widget.graffiti.GraffitiView
import com.jty.lib_base.widget.graffiti.IGraffitiTouchDetector
import com.jty.module_main.BR
import com.jty.module_main.R
import com.jty.module_main.databinding.MainFragmentPreviewBinding
import com.jty.module_main.viewmodel.PreviewViewModel
import com.kongzue.dialogx.dialogs.WaitDialog
import com.orhanobut.logger.Logger
import com.tstudy.blepenlib.data.BleDevice
import com.tstudy.blepenlib.data.CoordinateInfo
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import okhttp3.RequestBody
import java.io.File
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.TimeUnit
import java.util.regex.Matcher
import java.util.regex.Pattern


@Route(path = AppConstants.Router.Main.F_PREVIEW)
class MainPreviewFragment : BaseFragment<MainFragmentPreviewBinding, PreviewViewModel>() {

    private val mQDots: ConcurrentLinkedQueue<CoordinateInfo> = ConcurrentLinkedQueue<CoordinateInfo>()
    private var mCurDot: CoordinateInfo? = null
    private var mGraffitiView: GraffitiView? = null
    private var mGraffitiTouchGestureListener: GraffitiOnTouchGestureListener? = null
    private var mDoodleBitmap: Bitmap? = null
    private var mIsDraw = false //用于记录是否涂鸦过，没有涂鸦就不需要保存
    private val mGridPictureList = mutableListOf<GridPictureBean>() //将所有涂鸦的图片保存起来，退出时上传数据
    private var mTemp_x = 0f //暂存转换后的坐标
    private var mTemp_y = 0f
    @Volatile private var  mIsLoadingImg = false
    private var mIsSubmit = false
    private var mIsFinishing = false
    private var uploadCount = 0
    private var mGridPicture:GridPictureBean? = null
    private var mGridPicture_temp:GridPictureBean? = null
    private var mScale = 1.0f
    private var mPrevImgPath = ""
    private var mCurImgPath = ""
    private val mCommitOfflineReqS = mutableListOf<CommitOfflineReq>()
    private var mMaxSort = 0
    private var mIsM1SaveImging = false //是否到了1分钟没有涂鸦，并且符合保存条件
    private var mM1Disposable: Disposable? = null //用于取消定时

    private var mIsFirstWriteRecord = false

    private val mKillDots = mutableListOf<CoordinateInfo>()
    private var mIsHasDown = false
    private var mAllowWrite_temp = 0


    private val mTsdListener: TsdService.OnDataReceiveListener = object : TsdService.OnDataReceiveListener {
        override fun onErrTsdPen(code: Int, msg: String?) {}

        override fun onOffDrawEnd() {}

        override fun onRefreshScan(isScaning: Boolean) {}

        override fun onAddDevice(bleDevice: BleDevice?) {}

        override fun onPenConnectStatus(code: Int, bleDevice: BleDevice?) {}

        override fun onGetPenInfo(batteryPercent: Int, memoryPercent: Int, memoryByteNum: Int) {}

        override fun onCoordDraw(coordinateInfo: CoordinateInfo?) {
            if(mGraffitiView == null) {
                Logger.e("出错了，逻辑上不能为null")
                return
            }
            mQDots.offer(coordinateInfo)
            pollDots()
        }

        override fun onFinish() {
        }
    }

    override fun initContentView(): Int {
        return R.layout.main_fragment_preview
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun getIsBindTsdService(): Boolean {
        return true
    }

    override fun getTsdServiceDataReceiveListener(): TsdService.OnDataReceiveListener? {
        return mTsdListener
    }

    override fun setTsdServiceConnected() {
        super.setTsdServiceConnected()
    }


    override fun initData() {
        super.initData()
        //禁止息屏
        requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        val list =  AppDatabase.getInstance().gridNoSubmitDao().getAll()
        if(list.isNotEmpty()) {
            Logger.e("-------自动保存的个数：：： ${list.size}")
            for(value in list) {
                mGridPictureList.add(GridPictureBean(value.id.toInt(), value.pageserial, value.pageNumber, value.pictureName!!, value.pictureUrl, value.width, value.height, value.bookId))
            }
        }
        mMaxSort = AppDatabase.getInstance().gridNoSubmitDao().getMaxSort()
        val killDots = AppDatabase.getInstance().coordinateKillDao().getAll()
        Logger.e("----------------上次杀死进程前没有保存的笔划数：${killDots.size}")
        for(value in killDots) {
            var kills = GsonUtils.fromJson<List<CoordinateInfo>>(value.strCoorDownToUp,
                object : TypeToken<List<CoordinateInfo>>() {}.getType())
            for(k in kills) {
                mQDots.offer(k)
            }

        }


        val id = arguments?.getInt("id", 0)?:0
        val lastIndex = arguments?.getInt("lastIndex", 0)?:0
        val totalPage = arguments?.getInt("totalPage", 0)?:0
        val bookName = arguments?.getString("bookName", "")?:""
        val pageAddress = arguments?.getString("pageAddress", "")?:""
        if(id == 0) {
            viewModel.getNoteTemplateInfo1(pageAddress)
        } else {
            viewModel.bookNoteByTeacherId(id, lastIndex, bookName, totalPage)
        }

        binding.btnCurIndex.setOnEditorActionListener(object : TextView.OnEditorActionListener{
            override fun onEditorAction(p0: TextView?, p1: Int, p2: KeyEvent?): Boolean {
                Logger.i("回车键的值：${p1}")
                if(!mIsM1SaveImging && !mIsLoadingImg && !mIsSubmit && mQDots.isNullOrEmpty() && mGraffitiView != null) {
                    if (p1 == EditorInfo.IME_ACTION_GO) {
                        var str = p0?.text?.trim().toString()?:"".toString()
                        while(str.startsWith("0")) {
                            str = str.substring(1, str.length)
                        }
                        val reg = "^[1-9]\\d*\$"
                        val pattern: Pattern = Pattern.compile(reg) //创建模式对象
                        val matcher: Matcher = pattern.matcher(str) //创建匹配器
                        if(!matcher.matches()) {
                            showNormalToast("请输入整数")
                            return false
                        }
                        val num = viewModel.findIndexByPage(str.toInt())
                        if(num == -1) {
                            showNormalToast("没找到对应的页码")
                            return false
                        }
                        if(!mIsM1SaveImging && !mIsLoadingImg && !mIsSubmit && mQDots.isNullOrEmpty()) {
                            setPhotoViewIndex(num)
                        } else {
                            if(mIsM1SaveImging) {
                                showNormalToast("正在自动保存图片，请稍后再试")
                            } else {
                                showNormalToast("正在绘制，请稍后再试")
                            }
                        }
                    }
                }
                return false
            }

        })
    }

    override fun onDestroyView() {
        //禁止息屏
        requireActivity().window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onDestroyView()
    }

    fun setModuel() {
        if(mGraffitiView == null) {
            showNormalToast("加载数据失败")
            this.activity?.finish()
            return
        }
        if(mTsdServiceBinder?.on_getmModule() != TsdService.MODULE_PEN_PREVIEW) {
            mTsdServiceBinder?.on_setmModule(TsdService.MODULE_PEN_PREVIEW)
        }
    }

    override fun onBackPressedSupport(): Boolean {
        //return super.onBackPressedSupport()
        onBackClick()
        return true
    }

    override fun initViewObservable() {
        super.initViewObservable()
        viewModel.uc.clickPreOrNext.observe(this) {
            Logger.e("点击了上下按钮------")
            if(!mIsM1SaveImging && !mIsLoadingImg && !mIsSubmit && mQDots.isNullOrEmpty() && mGraffitiView != null) {
                /*if(mIsDraw && mIsLoadingImg) {
                    return@observe
                }
                mIsLoadingImg = false
                mIsDraw = false*/

                if(it) {
                    val num = viewModel.gridPictureBeanList.value!!.get(viewModel.mCurIndex).pageNumber + 1
                    val index = viewModel.findIndexByPage(num)
                    if(index != -1) {
                        setPhotoViewIndex(index)
                    }
                } else {
                    val num = viewModel.gridPictureBeanList.value!!.get(viewModel.mCurIndex).pageNumber - 1
                    val index = viewModel.findIndexByPage(num)
                    if(index != -1) {
                        setPhotoViewIndex(index)
                    }
                }
            }
        }
        viewModel.uc.getDataFailByAddress.observe(this) {
            mIsLoadingImg = false
            whilePollUntileUp()
            if(viewModel.getGridPictureSize() > 0) {
                pollDots()
            } else {
                mQDots.clear()
            }

        }
        viewModel.uc.onFinish.observe(this) {
            onBackClick()
        }

        viewModel.gridPictureBeanList.observe(this) {
            /*var urlList = mutableListOf<String>()
            for (item in viewModel.gridPictureBeanList.value!!) {
                var url: String = ""
                val imgPath= getPicFilePath(
                    viewModel.model.getUserId()!!,
                    "gridPicture",
                    "" + item.id,
                    ""
                )
                val file = File(imgPath)
                if(file.exists()) {
                    url = imgPath!!
                } else {
                    url = item.pictureUrl
                }
                urlList.add(url)
            }*/


            if(viewModel.getGridPictureSize() > 0) {
                binding.tvTotalPage.setText("/" + viewModel.mTotalPage)
                setPhotoViewIndex(viewModel.mCurIndex)
            } else {
                mQDots.clear()
            }
        }
    }

    fun setPhotoViewIndex(index: Int) {
        viewModel.setmCurIndex(index)
        binding.btnCurIndex.setText(viewModel.getCurGridPicture().pageNumber.toString())

        mGridPicture?.let{
            mPrevImgPath = getPicFilePath(
                viewModel.model.getUserId()!!,
                "gridPicture",
                "" + PageserialUtils.pageserialToFileName(it.pageserial),
                ""
            )!!
        }

        mGridPicture = viewModel.getCurGridPicture()

        mGridPicture?.let{
            mCurImgPath = getPicFilePath(
                viewModel.model.getUserId()!!,
                "gridPicture",
                "" + PageserialUtils.pageserialToFileName(it.pageserial),
                ""
            )!!
            if(mPrevImgPath.isNullOrBlank()) {
                mPrevImgPath = mCurImgPath
            }
        }


        mIsLoadingImg = true
        mM1Disposable?.let {
            if(!it.isDisposed) {
                it.dispose()
            }
        }
        if(mIsDraw) {
            savePic()
        } else {
            changePic()
        }

    }

    private fun onBackClick() {
        if(mIsFinishing || mIsSubmit) {
            return
        }
        mIsFinishing = false
        if(mQDots.isNullOrEmpty()) {
            isToSubmit()
        } else {
            mIsFinishing = true
            mM1Disposable?.let {
                if(!it.isDisposed) {
                    it.dispose()
                }
            }
        }
    }

    private fun isToSubmit() {
        if(mGridPictureList.isNullOrEmpty()) {
            requireActivity().finish()
        } else {
            WaitDialog.show("正在上传数据")
            mIsSubmit = true
            mIsFinishing = false
            mM1Disposable?.let {
                if(!it.isDisposed) {
                    it.dispose()
                }
            }
            if (mGraffitiView != null) {
                if(mIsDraw) {
                    savePic()
                } else {
                    uploadImg()
                }
            }else {
                //没有涂鸦，但是有上次异常退出保存的数据
                uploadImg()
            }
        }
    }

    private fun savePic() {
        if (mGraffitiView != null) {
            mGraffitiView!!.save()
        }
    }

    private fun changePic() {
        viewModel.getCurGridPicture().let{
            val screenWidth = ScreenUtils.getScreenWidth()
            mScale = screenWidth * TsdService.IMG_SCALE / it.width
            val realWidth = it.width * mScale
            val realHeight = it.height * mScale
            Logger.i("屏幕宽：$screenWidth, 图片的高：${it.width}, scale: $mScale，转换宽：${realWidth}, 转换高: $realHeight")

            downLoadImg(it, realWidth, realHeight)
        }
    }

    private fun downLoadImg(t:GridPictureBean, realWidth: Float, realHeight: Float) {
        val imgPath= getPicFilePath(
            viewModel.model.getUserId()!!,
            "gridPicture",
            "" + PageserialUtils.pageserialToFileName(t.pageserial),
            ""
        )
        var url = ""
        val imgFile: File = File(imgPath)
        if(imgFile.exists()) {
            url = imgPath!!
        } else {
            url = t.pictureUrl
        }
        Glide.with(this).asBitmap().load(url).skipMemoryCache(true)
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .override(realWidth.toInt(), realHeight.toInt())
            .into(object : CustomTarget<Bitmap?>() {
                override fun onResourceReady(
                    resource: Bitmap,
                    transition: Transition<in Bitmap?>?
                ) {
                    Logger.e("m1:Glde图片-成功  = " + url)
                    mDoodleBitmap = resource
                    initGraffitiData()
                }

                override fun onLoadFailed(errorDrawable: Drawable?) {
                    super.onLoadFailed(errorDrawable)
                    Logger.e("m1:Glde图片-失败  = " + url)
                }

                override fun onLoadCleared(placeholder: Drawable?) {}
            })
    }

    private fun initGraffitiData() {
        binding.flDoodle.removeAllViews()

        mGraffitiView = GraffitiView(
            this.activity,
            mDoodleBitmap,
            null,
            false,
            false,
            object : GraffitiView.IGraffitiViewListener {
                override fun onSaved(bitmaps: MutableList<Bitmap>?) {
                    Logger.i("m1:涂鸦保存成功")
                    mIsDraw = false

                    Observable.create<Int> { emitter ->
                        saveBitmap(bitmaps!![0], if(mIsSubmit || mIsM1SaveImging)mCurImgPath else mPrevImgPath)
                        emitter.onNext(1)
                        emitter.onComplete()
                    }.compose(bindToLifecycle()).subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(object : Observer<Int?> {
                            override fun onSubscribe(d: Disposable) {
                            }

                            override fun onNext(t: Int) {
                                if(mIsSubmit) {
                                    mIsLoadingImg = false
                                    uploadImg()
                                } else if(mIsLoadingImg){
                                    changePic()
                                } else if(mIsM1SaveImging) {
                                    mIsM1SaveImging = false
                                    showNormalToast("自动保存成功")
                                    Logger.i("自动保存图片成功")
                                } else {
                                    Logger.e("出错了， 不符合条件")
                                }
                                AppDatabase.getInstance().coordinateKillDao().deleteAll()
                            }

                            override fun onError(e: Throwable) {
                            }

                            override fun onComplete() {
                            }
                        })

                }
            })
        mGraffitiTouchGestureListener = GraffitiOnTouchGestureListener(
            mGraffitiView,
            object : GraffitiOnTouchGestureListener.IGraffitiOnTouchGestureListener {
                override fun onTest() {
                }

                override fun onLongPress(e: MotionEvent?) {
                }

                override fun onCallScroll(
                    e1: MotionEvent?,
                    e2: MotionEvent?,
                    distanceX: Float,
                    distanceY: Float
                ) {
                    //Logger.i("m1:滚动手指：distanceX: $distanceX, distanceY:$distanceY")
                }

            })
        val detector: IGraffitiTouchDetector =
            GraffitiTouchDetector(this.activity, mGraffitiTouchGestureListener)
        mGraffitiView?.setDefaultTouchDetector(detector)
        mGraffitiTouchGestureListener?.setSupportScale(false) //禁止放大缩小
        setSupportDoodle(false)
        setSupportTrans(false)
        mGraffitiTouchGestureListener?.setTouchType(GraffitiOnTouchGestureListener.TOUCH_TYPE_ALL)


        //mGraffitiView.setStartXy(true);
        mGraffitiView?.setColor(Color.BLACK)
        mGraffitiView?.setIsDrawableOutside(false)
        mGraffitiView?.setSize(2f)
        /*val layoutParams = binding.flDoodle.getLayoutParams()
        layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT;
        layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT;*/
        binding.flDoodle.addView(
            mGraffitiView,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        delayToDot(300)
    }

    private fun setSupportDoodle(isSupport: Boolean) {
        mGraffitiTouchGestureListener?.setSupportGraffiti(isSupport)
    }

    private fun setSupportTrans(isSupport: Boolean) {
        mGraffitiTouchGestureListener?.setSupportTrans(isSupport)
    }

    fun delayToDot(time: Long) {
        Observable.timer(time.toLong(), TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .compose(bindToLifecycle())
            .subscribe(object : Observer<Long> {
                override fun onSubscribe(d: Disposable) {}
                override fun onNext(aLong: Long) {
                    mIsLoadingImg = false
                    if(mCurDot != null && !mQDots.isNullOrEmpty()) {
                        drawTrack_real(mCurDot!!)
                    } else if(!mQDots.isNullOrEmpty()) {
                        pollDots()
                    }
                    setModuel()
                }

                override fun onError(e: Throwable) {}
                override fun onComplete() {}
            })
    }

    private fun whilePollUntileUp() {
        while (!mQDots.isEmpty()) {
            val info = mQDots.poll()
            if (info.state == TsdService.PEN_UP_MESSAGE.toInt()) {
                break
            }
            //循环弹出数据，直到弹出下一个弹起数据
        }
    }

    private fun pollDots() {
        if(mIsLoadingImg) {
            return
        }
        if(mIsM1SaveImging) {
            return
        }
        if(mQDots.isNullOrEmpty()) {
            if(mIsFinishing) {
                isToSubmit()
            }
            return
        }
        mCurDot = mQDots.poll()
        if(mCurDot == null) {
            return
        }
        if(mGridPicture == null || mCurDot!!.pageAddress != mGridPicture!!.pageserial) {
            //找图片
            val gridPicture = AppDatabase.getInstance().gridPictureDao().queryByPageserial(mCurDot!!.pageAddress)
            if(gridPicture == null) {
                whilePollUntileUp()
                pollDots()
                return
            }
            mIsLoadingImg = true
            mM1Disposable?.let {
                if(!it.isDisposed) {
                    it.dispose()
                }
            }
            //查看是不是同一本书
            if(gridPicture.bookNoteId == viewModel.mBookId.toLong()) {
                //是同一本书
                val index = viewModel.findIndexByPageAddress(gridPicture.pageserial)
                if(index == -1) {
                    whilePollUntileUp()
                    pollDots()
                    return
                }
                setPhotoViewIndex(index)
                if(!mIsFirstWriteRecord) {
                    createTeacherWriteRecord(gridPicture.bookNoteId!!.toInt());
                }
            }else {
                //不是同一本书
                viewModel.getNoteTemplateInfo1(gridPicture.pageserial)
                createTeacherWriteRecord(gridPicture.bookNoteId!!.toInt());
            }
        } else {
            if(!mIsFirstWriteRecord) {
                createTeacherWriteRecord(mGridPicture!!.bookId!!.toInt());
            }
            //去绘制
            drawTrack_real(mCurDot!!)
        }
    }

    private fun drawTrack_real(dot: CoordinateInfo) {
        if(viewModel.mAllowWrite > 0) {
            if(mAllowWrite_temp != viewModel.mAllowWrite) {
                mAllowWrite_temp = viewModel.mAllowWrite
                if(mAllowWrite_temp == 1) {
                    showNormalToast("请使用对应区域的教研本")
                } else if(mAllowWrite_temp == 2) {
                    showNormalToast("请使用对应学校的教研本")
                }
            }
            pollDots()
            return
        }else {
            mAllowWrite_temp = 0
        }
        mTemp_x = TsdPenUtil.getRealX(dot.coordX.toFloat(), mGridPicture!!.width) * mScale
        mTemp_y = TsdPenUtil.getRealY(dot.coordY.toFloat(), mGridPicture!!.height) * mScale

        mKillDots.add(dot)

        if (dot.state == TsdService.PEN_DOWN_MESSAGE) {
            mIsHasDown = true
            mGraffitiTouchGestureListener!!.r_onDown(mTemp_x, mTemp_y)
            mGraffitiTouchGestureListener!!.r_onScrollBegin(mTemp_x, mTemp_y)

            if(!mIsDraw)mIsDraw = true
            mM1Disposable?.let {
                if(!it.isDisposed) {
                    it.dispose()
                }
            }

            if(!mIsFinishing && !mIsSubmit && !mIsLoadingImg) {
                delayAutoSave()
            }

            if(mGridPicture_temp == null || mGridPicture_temp!!.pageserial != mGridPicture!!.pageserial) {
                mGridPicture_temp = mGridPicture
                for((index, value) in mGridPictureList.withIndex()) {
                    if(value.pageserial == dot.pageAddress) {
                        mGridPictureList.remove(value)
                        break
                    }
                }
                mGridPictureList.add(mGridPicture!!)

                mMaxSort++
                var gridNoSubmit = AppDatabase.getInstance().gridNoSubmitDao().queryByPageserial(mGridPicture!!.pageserial)
                if(gridNoSubmit == null) {
                    gridNoSubmit = GridNoSubmit(mGridPicture!!.id.toLong(), mGridPicture!!.pageserial, mGridPicture!!.pageNumber, mGridPicture!!.pictureName, mGridPicture!!.pictureUrl, mGridPicture!!.width, mGridPicture!!.height, mGridPicture!!.bookId, mMaxSort)
                    AppDatabase.getInstance().gridNoSubmitDao().insertAll(gridNoSubmit)
                } else {
                    gridNoSubmit.sort = mMaxSort
                    AppDatabase.getInstance().gridNoSubmitDao().updateGridNoSubmit(gridNoSubmit)
                }


                val g = AppDatabase.getInstance().gridPictureDao().queryByPageserial(mGridPicture!!.pageserial)
                g?.bookNoteId?.let{
                    val b = AppDatabase.getInstance().bookNoteDao().queryById(it)
                    b?.let { itt ->
                        itt.lastPageNum = mGridPicture!!.pageNumber
                        AppDatabase.getInstance().bookNoteDao().updateBookNotes(itt)

                    }
                }

            }




        } else if (dot.state == TsdService.PEN_COODINAT_MESSAGE) {
            if(mIsHasDown) {
                mGraffitiTouchGestureListener!!.r_onScroll(mTemp_x, mTemp_y)
            }
        } else if (dot.state == TsdService.PEN_UP_MESSAGE) {
            if(mIsHasDown) {
                mIsHasDown = false
                mGraffitiTouchGestureListener!!.r_onScrollEnd(mTemp_x, mTemp_y)

                AppDatabase.getInstance().coordinateKillDao()
                    .insert(CoordinateKill(null, GsonUtils.toJson(mKillDots)))
                mKillDots.clear()
            }
        }

        pollDots()
    }

    private fun uploadImg() {
        if(mGridPictureList.size == 0) {
            mIsSubmit = false
            return
        }
        mCommitOfflineReqS.clear()
        uploadCount = 0
        //WaitDialog.show("正在上传数据")
        uploadImg_http()
    }
    private fun uploadImg_http() {
        if(uploadCount != mGridPictureList.size) {
            val imgPath= getPicFilePath(
                viewModel.model.getUserId()!!,
                "gridPicture",
                "" + PageserialUtils.pageserialToFileName(mGridPictureList.get(uploadCount).pageserial),
                ""
            )
            if(!File(imgPath).exists()) {
                WaitDialog.dismiss()
                mIsSubmit = false
                requireActivity().finish()
                return
            }
            val uploadPath = "${viewModel.model.getUserId()!!}_${PageserialUtils.pageserialToFileName(mGridPictureList.get(uploadCount).pageserial)}_${System.currentTimeMillis()}.png"
            UploadOss.getInstance()?.upload2OSS(uploadPath, imgPath!!, onUploadListener, null)
        } else {
            commitTeacherBookNote()
        }
    }

    private fun commitTeacherBookNote() {
        val requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
            GsonUtils.toJson(mCommitOfflineReqS))

        viewModel.model.apply {
            commitTeacherBookNote(requestBody)
                .compose(RxThreadHelper.rxSchedulerHelper(viewModel))
                .subscribe(object : ApiSubscriptHelper<BaseBean<Any?>>() {
                    override fun onResult(t: BaseBean<Any?>) {
                        //Logger.e(t.toString())
                        WaitDialog.dismiss()
                        mIsSubmit = false
                        if (t.code == 0) {
                            showNormalToast("上传成功")
                            AppDatabase.getInstance().gridNoSubmitDao().deleteAll()
                        }
                        requireActivity().finish()
                    }

                    override fun onFailed(msg: String?) {
                        WaitDialog.dismiss()
                        showNormalToast(msg)
                        mIsSubmit = false
                        requireActivity().finish()
                    }
                })
        }
    }

    val onUploadListener = object : UploadOss.OnUploadListener{
        override fun uploadSuccess(uploadFile: String?, localFile: String, ossParams: OssParams?): String? {
            mCommitOfflineReqS.add(CommitOfflineReq(uploadFile!!, mGridPictureList.get(uploadCount).pageserial))
            uploadCount++
            uploadImg_http()
            return null
        }

        override fun uploadFail(
            uploadFile: String?,
            localFile: String,
            ossParams: OssParams?,
        ): String? {
            uploadCount = 0
            WaitDialog.dismiss()
            mIsSubmit = false
            requireActivity().finish()
            return null
        }
    }

    fun delayAutoSave() {
        Observable.timer(15 * 1000, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .compose(bindToLifecycle())
            .subscribe(object : Observer<Long> {
                override fun onSubscribe(d: Disposable) {
                    mM1Disposable = d
                }
                override fun onNext(aLong: Long) {
                    Logger.i("开始自动保存")
                    if(mIsDraw) {
                        if(!mIsFinishing && !mIsLoadingImg && !mIsSubmit) {
                            mIsM1SaveImging = true
                            savePic()
                        }
                    }
                }

                override fun onError(e: Throwable) {}
                override fun onComplete() {}
            })
    }

    private fun createTeacherWriteRecord(id: Int) {
        mIsFirstWriteRecord = true
        Logger.i("-----教师书写前书写记录确认----${id}")
        val json = ComUtils.getHashmapByStr(
            arrayOf("id"),
            arrayOf(id)
        )
        val requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
            GsonUtils.toJson(json))

        viewModel.model.apply {
            createTeacherWriteRecord(requestBody)
                .compose(RxThreadHelper.rxSchedulerHelper(viewModel))
                .subscribe(object : ApiSubscriptHelper<BaseBean<Any?>>() {
                    override fun onResult(t: BaseBean<Any?>) {
                        if (t.code == 0) {

                        }
                    }
                    override fun onFailed(msg: String?) {

                        showNormalToast(msg)
                    }
                })
        }
    }

}